// 引入VueRouter
import VueRouter from "vue-router";

// 引入组件
import MainView from '@/views/MainView';
import LoginView from '@/views/login/LoginView';

// 创建路由器
const router = new VueRouter({
    // 配置路由
    routes: [
        {
            path: '/',
            component: MainView,
            meta: { 
                requiresAuth: true 
            },
            children: [
                {
                    path: '',
                    component: () => import('@/views/home/HomeView'),
                    meta: { 
                        requiresAuth: true 
                    }
                },
                {
                    path: 'home',
                    component: () => import('@/views/home/HomeView'),
                    meta: { 
                        requiresAuth: true 
                    }
                },
                {
                    path: 'user',
                    component: () => import('@/views/user/UserView'),
                    meta: { 
                        requiresAuth: true 
                    }
                },
                {
                    path: 'record',
                    component: () => import('@/views/record/RecordView'),
                    meta: { 
                        requiresAuth: true 
                    }
                },
                {
                    path: 'book',
                    component: () => import('@/views/book/BookView'),
                    meta: { 
                        requiresAuth: true 
                    }
                },
                {
                    path: 'addBook',
                    component: () => import('@/views/book/AddBook'),
                    meta: { 
                        requiresAuth: true 
                    }
                },
                {
                    path: 'addUser',
                    component: () => import('@/views/user/AddUser'),
                    meta: { 
                        requiresAuth: true 
                    }
                }
            ]
        },
        {
            path: '/login',
            component: LoginView
        }
    ]
})

// 定义全局前置路由守卫
router.beforeEach((to, from, next) => {
    const isLoggedIn = Boolean(localStorage.getItem('employee')); // 从localStorage中读取登录信息
    
    if (to.meta.requiresAuth && !isLoggedIn) { // 需要登录且未登录
        next('/login'); // 跳转到登录页面
    } else {
        next(); // 继续路由导航
    }
})

// 暴露路由器
export default router